<?php
/**
 * 系統名稱: Lotto 系統
 * 檔案說明: 專案管理-修改
 * $Author$
 * $Id$
 *
 */
 /*********************************************
傳入參數
Account：帳號
Password：密碼
sid：隨機亂數
***********************************************/
/*$arrIP = split(",", $_SERVER["HTTP_X_FORWARDED_FOR"]);
$IP = ($arrIP[0] != "")?$arrIP[0]:$_SERVER["REMOTE_ADDR"];
if($IP != "220.132.101.76" && $IP != "218.210.10.192"){
	print $IP;
	exit("現在在做系統調整，<br />18:00 重新開放 ，請稍後！不便之處請見諒！");
}*/
include_once("../config.inc.php");

session_start();
$_LangPath = "login_member";	//語言檔參數，務必放在最前面
if($strSuppleID == "")$_DBSite = "Query";
include_once(__Language_Path."/selectlanguage_member.php");
include_once(__DBConnect_File);
include_once(__Modules_Path."/LogRecord.lib.php");
include_once(__Modules_Path."/UserSessions.lib.php");
include_once(__Modules_Path."/Login.lib.php");
include_once(__Modules_Path."/Commission.lib.php");
include_once(__Common_Path."/ExchangeRate.inc.php");
include_once(__Common_Path."/SysParam.inc.php");
@include_once(__Root_Path."/web.inc.php");

$strFileVFD = __Common_Path."/VirtualHostForDirector.inc.php";
if(file_exists($strFileVFD))include($strFileVFD);

function isValid(&$strWorld){  //是否包含不合法字元
	if(strchr($strWorld, '%')) return true;
	if(strchr($strWorld, "'")) return true;
	if(strchr($strWorld, "#")) return true;
	if(strchr($strWorld, "`")) return true;
	return false;
}
$_KSysParam[ForceChangePWDDays] = 60;
$strRedirect = trim($_data["Redirect"]);
$strRdHttpHost = trim($_data["RdHttpHost"]);
//===========================================================================//
//$_data["sid"] = trim($_data["sid"]);
//if(empty($_data["sid"]))header("Location: /index.php");

//登入超過規定3次數
if($_SESSION["Member_LoginErrNo"] > 3){
	$GLOBALS["errormessage"] = $_strLogin["LoginOver3"];	//您已經登入失敗三次，請過半小時後再登入！
	ErrMsgOutputHTML("Error", "", 1);
}

if(time() <= $_SESSION["Member_Info"] -> ExistUserCheckTime && $_SESSION["Member_Info"] -> Account == $_data["Account"]){
	//print $_SESSION["Member_Info"] -> ExistUserCheckTime - time();
	$GLOBALS["errormessage"] = $_strLogin["isUsed"];	//請等待三分鐘後再一次嘗試登入！
	ErrMsgOutputHTML("Error", "", 1);
}

if($_SESSION["Member_Info"] -> isHidden != "Y" && preg_match("/^mm_/", $_data["Account"])){
	AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], -2);
	$GLOBALS["errormessage"] = $_strLogin["NotMember"];	//此帳號不屬於會員
	ErrMsgOutputHTML("Error", "", 1);
}
//===========================================================================//
//找出該會員資料
$_data["Account"] = trim($_data["Account"]);
$_data["Password"] = trim($_data["Password"]);
if($_data["Account"] == $_data["Password"]){
	header("Location: /member/game/game.php");
	exit();
}

if(isValid($_data["Account"]) || isValid($_data["Password"])){
	$_SESSION["Member_LoginErrNo"]++;
	AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], -10);
	$GLOBALS["errormessage"] = $_strLogin["ID&PWD_Err"]."<br />".$_SESSION["Member_LoginErrNo"]." times!!";	//帳號和密碼錯誤，請重新登入！
	ErrMsgOutputHTML("Error", "", 1);
}

$_strSQL = "select * from `bet_Member` where Account = '".$_data["Account"]."' limit 0,1";
//if($strSuppleID == "" || $_SESSION["Member_Info"] -> isHidden != "Y")$_strSQL .= " and Password = '".$_data["Password"]."' limit 0,1";
//SQL 指令出錯
if(!$RS = @PMA_mysql_query($_strSQL, $$_Conn)){
	$_SESSION["Member_LoginErrNo"]++;
	AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], 0);
	$GLOBALS["errormessage"] = $_strLogin["ID&PWD_Err"]."<br />".$_SESSION["Member_LoginErrNo"]." times!!";	//帳號和密碼錯誤，請重新登入！
	ErrMsgOutputHTML("Error", "", 1);
}

//找不到帳號密碼
if(PMA_mysql_num_rows($RS) == 0){
	if($_data["Account"] == $_data["Password"]){
		header("Location: /member/game/game.php");
		exit();
	}
	$_SESSION["Member_LoginErrNo"]++;
	@mysql_free_result($RS);
	AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], 0);
	$GLOBALS["errormessage"] = $_strLogin["ID&PWD_Err"]."<br />".$_SESSION["Member_LoginErrNo"]." times!!";	//帳號和密碼錯誤，請重新登入！
	ErrMsgOutputHTML("Error", "", 1);
}

$objMember = PMA_mysql_fetch_object($RS);
@mysql_free_result($RS);
//接收綁 domain 限制
if(sizeof($_arrGLink) > 0){// && $_WebDomain != $_SERVER["HTTP_HOST"]
	$strHost = strtolower($_SERVER["HTTP_HOST"]);
	$strHost = str_replace(".", "_", $strHost);

	if(!is_array($_arrGLink[$strHost])){
		$GLOBALS["errormessage"] = $_strLogin["ID&PWD_Err"]; //帳號和密碼錯誤，請重新登入！
		//$GLOBALS["errormessage"] = $_WebDomain." = ".$_SERVER["HTTP_HOST"]." = ".$strHost;
		print "<!--";
		print $_WebDomain." = ".$_SERVER["HTTP_HOST"]." = ".$strHost;
		print_r($_arrGLink);
		print "//-->";
		ErrMsgOutputHTML("Error", "", 1);
	}

	if(!in_array((int)$objMember -> DirectorID, $_arrGLink[$strHost])){
		$_SESSION["LoginErr_No"] ++;
		AddLogin_Log($_data["Account"], $_data["Password"], 5);
		$title = $_strLogin["Err"];
		$GLOBALS["errormessage"] = $_strLogin["ID&PWD_Err"];  //"帳號和密碼錯誤，請重新登入！"
		$isRedirectIndex = "y";
		ErrMsgOutputHTML("Error", "", 1);
	}
}

if($strSuppleID == "" || $_SESSION["Member_Info"] -> isHidden != "Y"){
	if($objMember -> Password !== $_data["Password"]){
		$_SESSION["Member_LoginErrNo"]++;
		@mysql_free_result($RS);
		AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], 0);
		$GLOBALS["errormessage"] = $_strLogin["ID&PWD_Err"]."<br />".$_SESSION["Member_LoginErrNo"]." times!!";	//帳號和密碼錯誤，請重新登入！
		ErrMsgOutputHTML("Error", "", 1);
	}
}

//此帳號停用
if($objMember -> isLock == 1){
	AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], -1);
	$GLOBALS["errormessage"] = $_strLogin["NoPower"];	//您的帳號已經被停用！
	ErrMsgOutputHTML("Error", "", 1);
}

//此帳號不屬於會員
if($objMember -> MemberGroup != 1){
	AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], -2);
	$GLOBALS["errormessage"] = $_strLogin["NotMember"];	//此帳號不屬於會員
	ErrMsgOutputHTML("Error", "", 1);
}

//===========================================================================//
//轉址動作
if($strRedirect != "y"){
	//if(file_exists(__Common_Path."/RedirectLink.inc.php"))include(__Common_Path."/RedirectLink.inc.php");
	if(file_exists("/home/share/common/RedirectLink.inc.php"))include("/home/share/common/RedirectLink.inc.php");
	if($arrRLink[$_SERVER["HTTP_HOST"]] != "" && $objMember -> SpGroup == 1){
		$strRLink = "http://".$arrRLink[$_SERVER["HTTP_HOST"]]."/member/login.php?Redirect=y&Account=".$_data["Account"]."&Password=".$_data["Password"]."&lang=".$_SESSION["Mem_LanguageNo"]."&RdHttpHost=".$_SERVER["HTTP_HOST"];
		$_SESSION["RdHttpHost"] = "";
		header("location: ".$strRLink);
		exit();
	}
}
$_SESSION["RdHttpHost"] = $strRdHttpHost;

//$objMember -> SID = $_data["sid"];
$flMemERate = (empty($_ECRate[$objMember -> ERID]["Rate"]))?1:$_ECRate[$objMember -> ERID]["Rate"];
$objMember -> MemExchangeRate = $flMemERate;
$objMember -> CreditLine = floor($objMember -> CreditLine / $flMemERate);
$objMember -> WagerType = 0;

$strCKey = $objMember -> ID."_".md5(time() + mt_rand(0, 10000));
setcookie("Member_CKey", $strCKey);
$objMember -> CKey = $strCKey;

//===========================================================================//
$intParentNo = 4; //會員上層數量
//找出上層資料
$strSQL = "select * from `bet_Member` where ID in (".$objMember -> SubID.", ".$objMember -> MainID.", ".$objMember -> StockID.", ".$objMember -> DirectorID.") order by MemberGroup limit 0, ".$intParentNo;
if(!$RS = PMA_mysql_query($strSQL, $$_Conn)){
	$GLOBALS["errormessage"] = "Find Agent Data Error!!";
	$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($$_Conn)."\nLine:".__LINE__."\nPage:".__FILE__;
	ErrMsgOutputHTML("Error", "", 1);
}
if(PMA_mysql_num_rows($RS) < $intParentNo){
	$GLOBALS["errormessage"] = "Not Find Agent Data!";
	$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($$_Conn)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
	ErrMsgOutputHTML("Error", "", 1);
}
$arrLayer[2] = array();
$arrLayer[3] = array();
$arrLayer[4] = array();
$arrLayer[5] = array();
while($Rows = PMA_mysql_fetch_object($RS)){
	if($Rows -> isLock == 1){	//若其中一層資料遭停用
		AddLogin_Log($_data["Account"], $_data["Password"], $Rows -> MemberGroup*-1);
		$title = $_strLogin["Err"];
		$GLOBALS["errormessage"] = $_strLogin["NoPower"];  //"您的帳號已經被停用，請和您的代理商聯繫！"
		ErrMsgOutputHTML("Error", "", 1);
	}elseif($Rows -> isLock == 2 && $objMember -> isLock == 0){ //若上曾有人遭停押，下層一律停押
		$objMember -> isLock = $Rows -> isLock;
	}
	if($Rows -> CreditLine < $objMember -> CreditLine)$objMember -> CreditLine = 1;

	$objMember -> LayerAcc[$Rows -> MemberGroup] = $Rows -> Account;
	switch($Rows -> MemberGroup){
		case 2:
			if($Rows -> isBlack > 0 && ($Rows -> isBlack < $objMember -> isBlack || $objMember -> isBlack == 0))$objMember -> isBlack = $Rows -> isBlack;
			$objMember -> SubCreditLine = $Rows -> CreditLine;
			$objMember -> SubScale = (1 - $Rows -> Rate1);
			$objMember -> MainScale = (1 - ($Rows -> Rate1 + $Rows -> Rate2));
			$objMember -> SubIsAutoSupple = $Rows -> isAutoSupple;
			$objMember -> SubAccount = $Rows -> Account;
			$arrLayer[2][2] = 1;
			$arrLayer[3][2] = 1;
			$arrLayer[4][2] = 1;
			$arrLayer[5][2] = 1;
			$arrLayer[2][3] = 1 - $Rows -> Rate2;
			$arrLayer[3][3] = 1;
			$arrLayer[4][3] = 1;
			$arrLayer[5][3] = 1;
			break;

		case 3:
			$objMember -> MainCreditLine = $Rows -> CreditLine;
			$objMember -> StockScale = $objMember -> MainScale - $Rows -> Rate1;
			$objMember -> MainIsAutoSupple = $Rows -> isAutoSupple;
			$objMember -> MainAccount = $Rows -> Account;
			$arrLayer[2][4] = $arrLayer[2][3] - $Rows -> Rate1;
			$arrLayer[3][4] = 1 - $Rows -> Rate1;
			$arrLayer[4][4] = 1;
			$arrLayer[5][4] = 1;
			break;

		case 4:
			$objMember -> StockCreditLine = $Rows -> CreditLine;
			$objMember -> StockIsAutoSupple = $Rows -> isAutoSupple;
			$objMember -> StockAccount = $Rows -> Account;
			$objMember -> DirectorScale = $objMember -> StockScale - $Rows -> Rate1;
			$objMember -> DirectorMaxScale = $Rows -> Rate2; //總監最多佔成
			$arrLayer[2][5] = $arrLayer[2][4] - $Rows -> Rate1;
			$arrLayer[3][5] = $arrLayer[3][4] - $Rows -> Rate1;
			$arrLayer[4][5] = 1 - $Rows -> Rate1;
			$arrLayer[5][5] = 1;
			break;

		case 5:
			$objMember -> DirectorIsAllowMaxRate = $Rows -> isAllowMaxRate;
			$objMember -> DirectorIsAutoSupple = $Rows -> isAutoSupple;
			$objMember -> DirectorAccount = $Rows -> Account;
			if($Rows -> isAllowMaxRate){
				$flTmp = $objMember -> StockScale - (1 - $Rows -> Rate1); // 剩餘成數 = 100 - 代理商 - 總代理 - 股東 - 公司最小成數
				if($flTmp > $objMember -> DirectorMaxScale)$flTmp = $objMember -> DirectorMaxScale; //若剩餘成數大於總監想要最多佔成
				$objMember -> DirectorScale = $objMember -> StockScale - $flTmp;

				$flTmp = $arrLayer[2][4] - (1 - $Rows -> Rate1); // 剩餘成數 = 100 - 總代理 - 股東 - 公司最小成數
				if($flTmp > $objMember -> DirectorMaxScale)$flTmp = $objMember -> DirectorMaxScale; //若剩餘成數大於總監想要最多佔成
				$arrLayer[2][5] = $arrLayer[2][4] - $flTmp;

				$flTmp = $arrLayer[3][4] - (1 - $Rows -> Rate1); // 剩餘成數 = 100 - 股東 - 公司最小成數
				if($flTmp > $objMember -> DirectorMaxScale)$flTmp = $objMember -> DirectorMaxScale; //若剩餘成數大於總監想要最多佔成
				$arrLayer[3][5] = $arrLayer[3][4] - $flTmp;

				$flTmp = $arrLayer[4][4] - (1 - $Rows -> Rate1); // 剩餘成數 = 100 - 公司最小成數
				if($flTmp > $objMember -> DirectorMaxScale)$flTmp = $objMember -> DirectorMaxScale; //若剩餘成數大於總監想要最多佔成
				$arrLayer[4][5] = $arrLayer[4][4] - $flTmp;
			}
			break;
	} //switch($Rows -> MemberGroup)
} //while($Rows = mysql_fetch_object($RS))

if($objMember -> DirectorScale <= 0 || $arrLayer[2][5] <= 0 || $arrLayer[3][5] <= 0 || $arrLayer[4][5] <= 0 || $arrLayer[5][5] <= 0){
	AddLogin_Log($_data["Account"], $_data["Password"], -6);
	$title = $_strLogin["Err"];
	$GLOBALS["errormessage"] = $_strLogin["PercentError"]."(".$objMember -> DirectorScale.")(".$objMember -> StockScale.")(".$objMember -> SubScale.")(".$objMember -> MainScale.")";  //"會員資料錯誤，其退水尚未設定！"
	ErrMsgOutputHTML("Error", "", 1);
}
$objMember -> LayerScale = $arrLayer;
//print_r($arrLayer);
//exit($objMember -> SubScale." = ".$objMember -> MainScale." = ".$objMember -> StockScale." = ".$objMember -> DirectorScale);
//===========================================================================//
$intBTNo = 28; //所有球類下注種類數量
//會員單場限額、單注限額
$strSQL = "(select * from `bet_MemberLimit` where MemID = ".$objMember -> ID." and LimitType in ('0', '1')) union ";
$strSQL .= "(select * from `bet_MemberLimit` where MemID in (".$objMember -> SubID.",".$objMember -> MainID.",".$objMember -> StockID.",".$objMember -> DirectorID.") and LimitType in (2, 3))";
if(!$RS = PMA_mysql_query($strSQL, $$_Conn)){
	$title = $_strLogin["Err"];
	$GLOBALS["errormessage"] = $_strLogin["NoCommission"]."2";  //"會員資料錯誤，其退水尚未設定！"
	ErrMsgOutputHTML("Error", "", 1);
}
$arrEventLimit = array();
$arrBetLimit = array();
$arrAcceptLimit = array();
$intEvent = 0;
while($Rows = PMA_mysql_fetch_object($RS)){
	if($Rows -> LimitType == 0){
		$arrEventLimit[$Rows -> LottoID][$Rows -> Bet_Type] = floor($Rows -> LimitValue / $objMember -> MemExchangeRate);
		$intEvent++;
	}elseif($Rows -> LimitType == 1){
		$arrBetLimit[$Rows -> LottoID][$Rows -> Bet_Type] = floor($Rows -> LimitValue / $objMember -> MemExchangeRate);
		$intEvent++;
	}elseif($Rows -> LimitType == 2){
		$arrAcceptLimit[$Rows -> LottoID][$Rows -> Bet_Type][$Rows -> MemID] = $Rows -> LimitValue;
	}elseif($Rows -> LimitType == 3){
		$arrAutoSuppleLimit[$Rows -> LottoID][$Rows -> Bet_Type][$Rows -> MemID] = $Rows -> LimitValue;
	}
} //while($Rows = mysql_fetch_object($RS))
if($intEvent < ($intBTNo*2)){
	$title = $_strLogin["Err"];
	$GLOBALS["errormessage"] = $_strLogin["NoCommission"]."(".$intEvent.")"."3";  //"會員資料錯誤，其退水尚未設定！"
	ErrMsgOutputHTML("Error", "", 1);
}
$objMember -> arrEventLimit = $arrEventLimit;
$objMember -> arrBetLimit = $arrBetLimit;
$objMember -> arrAcceptLimit = $arrAcceptLimit;
$objMember -> arrAutoSuppleLimit = $arrAutoSuppleLimit;

//===========================================================================//
//找出會員、代理商、總代理、股東退水
$strSQL = "select * from `bet_Commission` USE INDEX (MemID) where MemID in (".$objMember -> ID.",".$objMember -> SubID.",".$objMember -> MainID.",".$objMember -> StockID.",".$objMember -> DirectorID.") and Gamble_Type = ".$objMember -> GambleType;
if(!$RS = PMA_mysql_query($strSQL, $$_Conn)){
	$title = $_strLogin["Err"];
	$GLOBALS["errormessage"] = $_strLogin["NoCommission"]."4";  //"會員資料錯誤，其退水尚未設定！"
	ErrMsgOutputHTML("Error", "", 1);
}

$intComm = 0;
while($Rows = PMA_mysql_fetch_object($RS)){
	$arrCommission[$Rows -> MemID][$Rows -> LottoID][$Rows -> Bet_Type] = $Rows -> Commission;
	$intComm++;
}

$objMember -> arrCommission = $arrCommission[$objMember -> ID];
$objMember -> arrSubCommission = $arrCommission[$objMember -> SubID];
$objMember -> arrMainCommission = $arrCommission[$objMember -> MainID];
$objMember -> arrStockCommission = $arrCommission[$objMember -> StockID];
$objMember -> arrDirectorCommission = $arrCommission[$objMember -> DirectorID];
if($intComm < ($intBTNo*5)){
	$title = $_strLogin["Err"];
	$GLOBALS["errormessage"] = $_strLogin["NoCommission"]."5";  //"會員資料錯誤，其退水尚未設定！"
	ErrMsgOutputHTML("Error", "", 1);
}

//===========================================================================//
//找出該會員 退水轉賠率資料
$arrUserORate = getUserCommToOdds($objMember -> ID, 4, array());
if($arrUserORate === false)ErrMsgOutputHTML("Error", "", 1);
$objMember -> UserCommToOdds[4] = $arrUserORate;

//===========================================================================//
$arrDate =  split("-", $objMember -> ChangePWDDate);
$ChangePWDDate = date("Y-m-d", mktime(0, 0, 0, $arrDate[1], ($arrDate[2] + $_KSysParam["ForceChangePWDDays"]), $arrDate[0]));
if($_KSysParam["isForceChangePWD"] == 1 && date("Y-m-d") > $ChangePWDDate){
	$objMember -> isForceChangePWD = 1;
}else{
	$objMember -> isForceChangePWD = 0;
}
$objMember -> ReflashTime = 0;
$_SESSION["Member_Info"] = $objMember;

if($strSuppleID == ""){
	if($_SESSION["Member_Info"] -> isForceChangePWD == 1){
		//記錄登入成功 Log
		AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], 1);
		header("Location: /member/mem_password.php?Force=Yes");
		exit();

	}else{

		//使用這是否已存在於網站
		if(UserSessions_Exist(session_id(), $_SESSION["Member_Info"] -> ID, $_SESSION["Member_Info"] -> MemberGroup)){
			AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], 2);
			//AddData_Log($_SESSION["Member_Info"] -> ID, "帳號使用中！", $_SESSION["Member_Info"] -> GroupName."(".$_SESSION["Member_Info"] -> Account."--".$_SESSION["Member_Info"] -> Name.")此帳號已經被其他人使用！");
			$GLOBALS["errormessage"] = str_replace("{Mins}", $_KSysParam[isLimitMemberLoginWaitTime], $_strLogin["isUsed"]);	//您的帳號已經被其他人使用中！
			ErrMsgOutputHTML("Error", "", 1);
		}
		AddLogin_Log($_data["Account"].$strSuppleID, $_data["Password"], 1);
		$_SESSION["Member_Info"] -> ExistUserCheckTime = 0;
		//紀錄 Session
		$intSID = UserSession_Start(session_id(), $_SESSION["Member_Info"] -> ID, $_SESSION["Member_Info"] -> MemberGroup, $_SESSION["Member_Info"] -> SubID, $_SESSION["Member_Info"] -> MainID, $_SESSION["Member_Info"] -> StockID, $_SESSION["Member_Info"] -> DirectorID);

		if($intSID === false)ErrMsgOutputHTML("LoginError", "", 1);

		$_SESSION["Member_Info"] -> WagerCommonTime = time();
		header("Location: /member/lb_rule.php?sid=".$intSID);//http://".$_SERVER["HTTP_HOST"]."
		exit();
	}
}

$_SESSION["Member_Info"] -> SuppleID = $strSuppleID;
$_SESSION["Member_Info"] -> SuppleDomain = $strSuppleDomain;
?>